<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="400px"
      :before-close="handleClose"
    >
      <el-form
        ref="formData"
        :rules="rules"
        :model="formData"
        label-width="100px"
        label-postion="right"
        style="width: 300px"
        status-icon
      >
        <el-form-item label="标签名称:" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>

        <el-form-item label="分类名称:" prop="categoryId">
          <el-select v-model="formData.categoryId" clearable filterable>
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('formData')" size="mini"
            >确定</el-button
          >
          <el-button size="mini" @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import api from "@/api/label";

export default {
  props: {
    title: {
      //弹窗的标题
      type: String,
      default: "",
    },
    visible: {
      //弹出窗口
      type: Boolean,
      default: false,
    },
    formData: {
      //提交表单数据
      type: Object,
      default: {},
    },
    remoteClose: Function, //用于关闭窗口
    categoryList: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      rules: {
        name: [{ required: true, message: "请输入标签名称", trigger: "blur" }],
        categoryId: [
          { required: true, message: "请选择分类名称", trigger: "change" },
        ],
      },
    };
  },

  components: {},

  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitData();
        } else {
          return false;
        }
      });
    },
    submitData() {
      let resp = {};
      if (this.formData.id) {
        api.add(this.formData).then((res) => {
          resp = res;
        });
      } else {
        api.update(this.formData).then((res) => {
          resp = res;
        });
      }

      if (resp.code === 20000) {
        this.$message({
          message: "保存成功",
          type: "success",
        });
        this.handleClose();
      } else {
        this.$message({
          message: "保存失败",
          type: "error",
        });
      }
    },
    handleClose() {
      this.$refs["formData"].resetFields();
      this.remoteClose();
    },
  },
};
</script>

<style scoped>
</style>